package com.bestv.search.common.dataSource;

import com.bestv.search.common.cache.SystemCache;
import org.aspectj.lang.JoinPoint;

public class DynamicDataSourceAspect {
    private SystemCache systemCache;

    // 通过此切面设置不同的SiteCode，以使用不同的数据源
    public void before(JoinPoint joinPoint) throws Exception {
        boolean existDataSourceKey = false;
        Object args[] = joinPoint.getArgs();
        for (Object arg : args) {
            // 参数中存在SiteCode时，使用当前的SiteCode
            if (arg instanceof DataSourceKey) {
                existDataSourceKey = true;
                DataSourceContextHolder.setDataSourceKey((DataSourceKey) arg);
                break;
            }
        }

        // 参数中不存在SiteCode时，抛出异常
        if (!existDataSourceKey)
            throw new Exception("Must have DataSourceKey agrument in method "
                    + joinPoint.getSignature().getDeclaringType().getName() + "." + joinPoint.getSignature().getName());

        // 检查是否为当前驻地
        boolean isMgmtDataSourceKey = systemCache.getLocalDataSourceKey().equalsIgnoreCase(
                DataSourceContextHolder.getDataSourceKey().toString()) ? true : false;

        // 是否为管理的驻地
        if (!isMgmtDataSourceKey) {
            if (systemCache.getMgmtDataSourceKeyList() != null && systemCache.getMgmtDataSourceKeyList().size() > 0) {
                for (String key : systemCache.getMgmtDataSourceKeyList()) {
                    if (key.trim().equalsIgnoreCase(DataSourceContextHolder.getDataSourceKey().toString())) {
                        isMgmtDataSourceKey = true;
                        break;
                    }
                }
            }
        }

        // 当不是管理的DataSourceKey时，抛出异常
        if (!isMgmtDataSourceKey) {
            throw new Exception("DataSourceKey doesn't be management \""
                    + DataSourceContextHolder.getDataSourceKey().toString() + "\" "
                    + joinPoint.getSignature().getDeclaringType().getName() + "." + joinPoint.getSignature().getName());
        }
    }

    public void after(JoinPoint joinPoint) {
        DataSourceContextHolder.clearDataSourceKey();
    }

    public SystemCache getSystemCache() {
        return systemCache;
    }

    public void setSystemCache(SystemCache systemCache) {
        this.systemCache = systemCache;
    }
}
